package pay

import (
	"context"
	"go-demo/designpattern/adapter/pay/sdk"
)

// WechatAdapter 微信支付适配器
type WechatAdapter struct {
	client *sdk.WeChatPayClient
}

// NewWechatAdapter 创建微信支付适配器
func NewWechatAdapter(mchID, apiKey string) *WechatAdapter {
	return &WechatAdapter{
		client: &sdk.WeChatPayClient{
			MchID:  mchID,
			APIKey: apiKey,
		},
	}
}

// Name 支付
func (a *WechatAdapter) Name() string {
	return "WechatPay"
}

// Pay 支付
func (a *WechatAdapter) Pay(ctx context.Context, request *PaymentRequest) (*PaymentResponse, error) {
	// 转换请求参数
	req := sdk.WeChatPayRequest{
		OutTradeNo:     request.OrderID,
		TotalFee:       request.Amount * 100, // 微信支付以分为单位
		Body:           request.Description,
		TradeType:      "APP",
		SpbillCreateIP: "127.0.0.1", // 实际业务中获取真实IP
	}
	// 调用微信支付接口
	resp, err := a.client.ProcessWeChatPayment(req)
	if err != nil {
		return nil, err
	}
	// 转换响应参数
	// 将微信响应转换为统一响应
	success := resp.ReturnCode == "SUCCESS" && resp.ResultCode == "SUCCESS"
	return &PaymentResponse{
		Success:    success,
		PaymentID:  resp.PrepayID,
		StatusCode: resp.ErrorCode,
		Message:    resp.ErrorCodeDes,
	}, nil
}
